package com.gogowan.agroenterprise.widget.wheel;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.gogowan.agroenterprise.R;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;

/**
 * 省市县三级联动界面
 * 
 * @author Administrator
 *
 */
public class LocationWheelActivity extends Activity implements OnClickListener,
		OnWheelChangedListener {
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	private Button mBtnConfirm;
	private Button mBtnCancel;
	private ArrayList<AreaInfo> shengAL = new ArrayList<AreaInfo>();
	private HashMap<String, String> hm = new HashMap<String, String>();
	private boolean flag = false;
	private ArrayList<String> al = new ArrayList<String>();

	/**
	 * 所有省
	 */
	protected String[] mProvinceDatas;
	/**
	 * key - 省 value - 市
	 */
	protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/**
	 * key - 市 values - 区
	 */
	protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
	/**
	 * 当前省的名称
	 */
	protected String mCurrentProviceName;
	/**
	 * 当前市的名称
	 */
	protected String mCurrentCityName;
	/**
	 * 当前区的名称
	 */
	protected String mCurrentDistrictName = "";

	/**
	 * 解析省市区的数据
	 */

	protected void initProvinceDatas() {
		AssetManager asset = getAssets();
		try {
			InputStream input = asset.open("location_data.xml");
			// 创建一个解析xml的工厂对象
			SAXParserFactory spf = SAXParserFactory.newInstance();
			// 解析xml
			SAXParser parser = spf.newSAXParser();
			XmlParserHandler handler = new XmlParserHandler();
			parser.parse(input, handler);
			input.close();
			// 获取解析出来的数据
			shengAL = handler.getDataList();

			mProvinceDatas = new String[shengAL.size()];
			for (int i = 0; i < shengAL.size(); i++) {
				// 遍历所有省的数据
				hm.put(shengAL.get(i).getAreaName(), shengAL.get(i)
						.getAreaCode());// 将省信息放入hashmap
				mProvinceDatas[i] = shengAL.get(i).getAreaName();
				List<AreaInfo> cityList = shengAL.get(i).getChildList();
				String[] cityNames = new String[cityList.size()];
				for (int j = 0; j < cityList.size(); j++) {
					// 遍历省下面的所有市的数据
					hm.put(cityList.get(j).getAreaName(), cityList.get(j)
							.getAreaCode());// 将市信息放入hashmap
					cityNames[j] = cityList.get(j).getAreaName();
					List<AreaInfo> districtList = cityList.get(j)
							.getChildList();
					String[] distrinctNameArray = new String[districtList
							.size()];
					for (int k = 0; k < districtList.size(); k++) {
						// 遍历市下面所有区/县的数据并存储
						hm.put(cityNames[j] + districtList.get(k).getAreaName(),
								districtList.get(k).getAreaCode());// 将县信息放入hashmap
						distrinctNameArray[k] = districtList.get(k)
								.getAreaName();
					}
					// 市-区/县的数据，保存到mDistrictDatasMap
					mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
				}
				// 省-市的数据，保存到mCitisDatasMap
				mCitisDatasMap.put(shengAL.get(i).getAreaName(), cityNames);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.wheel_location_activity);

		LocationWheelActivity.this.overridePendingTransition(R.anim.bottom_in,
				R.anim.bottom_out);

		// WindowManager m = getWindowManager();
		// Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高

		LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
		getWindow().setGravity(Gravity.LEFT | Gravity.BOTTOM);
		p.x = 0; // 新位置X坐标
		p.y = 0; // 新位置Y坐标
		// p.height = (int) (d.getHeight() * 0.3); // 高度设置为屏幕的1.0
		// p.width = (int) (d.getWidth() - 40); // 宽度设置为屏幕的0.8
		// p.alpha = 1.0f; // 设置本身透明度
		// p.dimAmount = 1.5f; //设置黑暗度

		getWindow().setAttributes(p); // 设置生效

		setUpViews();
		setUpListener();
		setUpData();
		flag = true;
	}

	private void setUpViews() {
		mViewProvince = (WheelView) findViewById(R.id.id_province);
		mViewCity = (WheelView) findViewById(R.id.id_city);
		mViewDistrict = (WheelView) findViewById(R.id.id_district);
		mBtnConfirm = (Button) findViewById(R.id.btn_confirm);
		mBtnCancel = (Button) findViewById(R.id.btn_cancel);
	}

	private void setUpListener() {
		// 添加change事件
		mViewProvince.addChangingListener(this);
		// 添加change事件
		mViewCity.addChangingListener(this);
		// 添加change事件
		mViewDistrict.addChangingListener(this);
		// 添加onclick事件
		mBtnConfirm.setOnClickListener(this);
		// 添加onclick事件
		mBtnCancel.setOnClickListener(this);
	}

	/**
	 * 整理数据
	 * 
	 * @author Administrator
	 * 
	 */
	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(
				LocationWheelActivity.this, mProvinceDatas));
		al = getIntent().getStringArrayListExtra("locationContent");
		// 设置可见条目数量
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		mViewDistrict.setVisibleItems(7);
		if (al != null && al.size() > 0)
			mViewProvince.setCurrentItem(Integer.parseInt(al.get(6)));
		updateCities();
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (flag) {
			if (wheel == mViewProvince) {
				updateCities();
			} else if (wheel == mViewCity) {
				updateAreas();
			} else if (wheel == mViewDistrict) {
				mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			}
		}
	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict
				.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		if (flag == false && al != null && al.size() > 0) {
			mViewDistrict.setCurrentItem(Integer.parseInt(al.get(8)));
			mCurrentDistrictName = al.get(4);
		} else {
			mViewDistrict.setCurrentItem(0);
			mCurrentDistrictName = areas[0];
		}
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		if (flag == false && al != null && al.size() > 0) {
			mViewCity.setCurrentItem(Integer.parseInt(al.get(7)));
		} else {
			mViewCity.setCurrentItem(0);
		}
		updateAreas();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_confirm:
			showSelectedResult();
			break;
		case R.id.btn_cancel:
			LocationWheelActivity.this.finish();
			LocationWheelActivity.this.overridePendingTransition(R.anim.bottom_out1,
					R.anim.bottom_in1);
			break;
		}
	}

	/**
	 * 将选中的结果返回到原activity
	 */
	private void showSelectedResult() {
		// Toast.makeText(
		// LocationWheelActivity.this,
		// "当前选中:" + mCurrentProviceName + "," + mCurrentCityName + ","
		// + mCurrentDistrictName,
		// Toast.LENGTH_SHORT).show();
		ArrayList<String> al2 = new ArrayList<String>();
		al2.add(mCurrentProviceName);
		al2.add(hm.get(mCurrentProviceName));
		al2.add(mCurrentCityName);
		al2.add(hm.get(mCurrentCityName));
		al2.add(mCurrentDistrictName);
		al2.add(hm.get(mCurrentCityName + mCurrentDistrictName));
		al2.add(mViewProvince.getCurrentItem() + "");
		al2.add(mViewCity.getCurrentItem() + "");
		al2.add(mViewDistrict.getCurrentItem() + "");
		Intent aintent = new Intent();
		aintent.putStringArrayListExtra("location", al2);
		setResult(RESULT_OK, aintent);

		LocationWheelActivity.this.finish();
		LocationWheelActivity.this.overridePendingTransition(R.anim.bottom_out1,
				R.anim.bottom_in1);
	}

	/**
	 * 返回
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)// 返回键
		{
			LocationWheelActivity.this.finish();
			LocationWheelActivity.this.overridePendingTransition(R.anim.bottom_out1,
					R.anim.bottom_in1);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 点击空白处消失
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		LocationWheelActivity.this.finish();
		LocationWheelActivity.this.overridePendingTransition(R.anim.bottom_out1,
				R.anim.bottom_in1);
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (shengAL != null) {
			shengAL.clear();
			shengAL = null;
		}
		if (hm != null) {
			hm.clear();
			hm = null;
		}
		if (mProvinceDatas != null) {
			mProvinceDatas = null;
		}
		if (mCitisDatasMap != null) {
			mCitisDatasMap.clear();
			mCitisDatasMap = null;
		}
		if (mDistrictDatasMap != null) {
			mDistrictDatasMap.clear();
			mDistrictDatasMap = null;
		}
	}
}
